﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.ComponentModel;
using System.Threading;

namespace Light.Utility
{
    /// <summary>
    /// 邮件发送类
    /// </summary>
    public class EmailHelper
    {
        /// <summary>
        /// 邮箱发送结果信息
        /// </summary>
        public static string Result { get; set; }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="email">邮件</param>
        /// <param name="isAsync">是否异步发送</param>
        public static bool Send(Email email, bool isAsync)
        {
            #region 邮件信息

            System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage();
            mailMsg.From = new MailAddress(email.FromAddress);

            foreach (var address in email.ToAddresses)
            {
                mailMsg.To.Add(address);
            }
            foreach (var filepath in email.Attachments)
            {
                mailMsg.Attachments.Add(new Attachment(filepath));
            }
            mailMsg.Subject = email.Title;
            mailMsg.Body = email.Content;
            mailMsg.BodyEncoding = Encoding.UTF8;
            mailMsg.IsBodyHtml = email.IsBodyHtml;
            mailMsg.Priority = System.Net.Mail.MailPriority.High;

            #endregion

            #region SMTP协议发送

            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();


            string[] infos = email.FromAddress.Split('@');
            string hostServer = infos[1].Split('.')[0];


            // 提供身份验证的用户名和密码
            // 网易邮箱用户可能为：username password
            // Gmail 用户可能为：username@gmail.com password
            if (String.IsNullOrEmpty(email.UserName))
            {
                email.UserName = infos[0];
            }
            smtp.Credentials = new System.Net.NetworkCredential(email.UserName, email.Password);

            smtp.Port = 25;       // Gmail 使用 465 和 587 端口, smtp端口为25; pop3端口为110;
            smtp.Host = "smtp." + hostServer.ToLower() + ".com";       // 如 smtp.163.com, smtp.gmail.com,smtp.qq.com
            smtp.EnableSsl = false; // 如果使用GMail，则需要设置为true

            try
            {
                if (isAsync)
                {
                    smtp.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(SendMailCompleted);
                    smtp.SendAsync(mailMsg, mailMsg);
                }
                else
                {
                    smtp.Send(mailMsg);
                    Result = "发送成功!";
                }
                return true;
            }
            catch (SmtpException ex)
            {
                Result = ex.Message;
                return false;
            }
            #endregion

        }

        /// <summary>
        /// 发送邮件（同步发送）
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static bool Send(Email email)
        {
            return Send(email, false);
        }

        static void SendMailCompleted(object sender, AsyncCompletedEventArgs e)
        {
            MailMessage mailMsg = (MailMessage)e.UserState;
            string subject = mailMsg.Subject;
            if (e.Cancelled) // 邮件被取消
            {
                Result = subject + " 被取消。";
            }
            if (e.Error != null)
            {
                Result = "错误：" + e.Error.ToString() + "。";
            }
            else
            {
                Result = "邮件发送成功。";
            }
        }
    }

    /// <summary>
    /// 邮件实体类
    /// </summary>
    public class Email
    {
        /// <summary>
        /// 发送邮箱的用户名[必填项]
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 发送邮箱的密码[必填项]
        /// </summary>
        public string Password { get; set; }

        /// <summary>
        /// 发送邮箱的邮箱地址[必填项]
        /// </summary>
        public string FromAddress { get; set; }

        /// <summary>
        /// 是否为HTML邮件
        /// </summary>
        public bool IsBodyHtml { get; set; }


        private List<string> toAddresses = new List<string>();

        /// <summary>
        /// 接收邮箱集合[必填项]
        /// </summary>
        public List<string> ToAddresses
        {
            get { return toAddresses; }
            set { toAddresses = value; }
        }

        /// <summary>
        /// 邮件标题
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// 邮件内容
        /// </summary>
        public string Content { get; set; }


        private List<string> attachments = new List<string>();

        /// <summary>
        /// 附件路径集合[可选项]
        /// </summary>
        public List<string> Attachments
        {
            get { return attachments; }
            set { attachments = value; }
        }

    }
}
